import 'package:flower/components/cached_image_widget.dart';
import 'package:flower/components/custom_toast.dart';
import 'package:flower/config/service_url.dart';
import 'package:flower/model/address_list.dart';
import 'package:flower/model/cart_list.dart';
import 'package:flower/model/coupon_model.dart';
import 'package:flower/model/submit.dart';
import 'package:flower/pages/tabs/shoppingcart/children/order_pay.dart';
import 'package:flower/pages/tabs/user/children/address_add.dart';
import 'package:flower/provider/address_model.dart';
import 'package:flower/provider/cart_model.dart';
import 'package:flower/utils/http_util.dart';
import 'package:flower/utils/my_colors.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:dio/dio.dart';

/* 订单提交页面 */
class OrderSubmit extends StatefulWidget {
  const OrderSubmit({super.key});

  @override
  State<OrderSubmit> createState() => _OrderSubmitState();
}

class _OrderSubmitState extends State<OrderSubmit> {
  List<CouponData> couponListData = [];
  final TextEditingController _remarkController = TextEditingController();

  @override
  void initState() {
    super.initState();
    queryCouponListData();
    queryAddressList();
  }

  // 获取可用优惠券列表
  void queryCouponListData() async {
    Response result = await HttpUtil.get(listByUser);
    CouponModel couponModel = CouponModel.fromJson(result.data);
    setState(() {
      // couponListData = couponModel.data!;
      context.read<CartModel>().setAvailableCoupons(couponModel.data);
    });
  }

  // 获取地址列表
  void queryAddressList() async {
    Response result = await HttpUtil.get(listAddress);
    AddressListModel addressListModel = AddressListModel.fromJson(result.data);
    setState(() {
      // addressListData = addressListModel.data!;
      context.read<AddressModel>().setAddressListData(addressListModel.data);
    });
  }


  // 提交订单
  void handleSubmitOrder() async {
    // 获取上下文外的 provider 数据时 listen 必须设置为 false
    final selectedAddress =
        Provider.of<AddressModel>(context, listen: false).getSelectedAddress();
    final cartIds =
        Provider.of<CartModel>(context, listen: false).getAllCartId();
    final selectedCoupon =
        Provider.of<CartModel>(context, listen: false).selectedCoupon;
    final discountPrice =
        Provider.of<CartModel>(context, listen: false).getDiscountPrice();

    // 将 cartIds 列表转换为逗号分隔的字符串
    String sidsString = cartIds.join(',');

    // 准备订单数据
    Map<String, dynamic> map = <String, dynamic>{};
    map["sids"] = sidsString;
    map["aid"] = selectedAddress?.id;
    map["cid"] = selectedCoupon?.id;
    map["amount"] = discountPrice;
    map["remark"] = _remarkController.value.text;

    Response result = await HttpUtil.post(submitOrder, queryParameters: map);
    SubmitModel submitModel = SubmitModel.fromJson(result.data);
    if (submitModel.code == 1) {
      CustomToast.showSuccessToast("创建订单成功！");
      SubmitData submitData = submitModel.data;

      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => OrderPay(
            amount: Provider.of<CartModel>(context, listen: false)
                .getDiscountPrice(),
            number: submitData.number,
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: const Text("创建订单"),
        titleTextStyle: const TextStyle(fontSize: 16, color: Colors.black),
        centerTitle: true,
      ),
      body: Container(
        height: MediaQuery.of(context).size.height,
        color: Colors.white,
        width: MediaQuery.of(context).size.width,
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            buildOrderDetail(),
            Positioned(bottom: 0, child: buildSubmit())
          ],
        ),
      ),
    );
  }

  // 底部弹出框
  void _openBottomSheetWithInfo(BuildContext context, String title) {
    showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return DraggableScrollableSheet(
          expand: false,
          builder: (BuildContext context, ScrollController scrollController) {
            if (title.contains("选择优惠券")) {
              return buildCouponList(context, scrollController);
            }
            if (title.contains("选择地址")) {
              return buildAddressList(context, scrollController);
            }
            return buildCouponList(context, scrollController);
          },
        );
      },
    );
  }

  // 地址列表
  ListView buildAddressList(BuildContext context, ScrollController controller) {
    List<AddressData> addressListData =
        Provider.of<AddressModel>(context, listen: false).getAllAddresses();

    return ListView.builder(
        controller: controller,
        itemCount: addressListData.length,
        itemBuilder: (BuildContext context, int index) {
          AddressData data = addressListData[index];
          var boxDecoration = BoxDecoration(
              border: Border.all(
                width: 1,
                color: Color(int.parse('fa436a', radix: 16)).withAlpha(255),
              ),
              borderRadius: const BorderRadius.all(Radius.circular(2)));
          return InkWell(
            onTap: () {
              // 设置为选中地址
              Provider.of<AddressModel>(context, listen: false)
                  .setSelectedAddress(data.id);
              Navigator.pop(context); // 返回上一页
            },
            child: Container(
              padding: const EdgeInsets.all(15),
              decoration: BoxDecoration(
                  border: Border(
                      top: BorderSide(
                          width: 1,
                          color: Color(int.parse('f5f5f5', radix: 16))
                              .withAlpha(255)))),
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Visibility(
                              visible: data.isDefault == 1,
                              child: Container(
                                margin: const EdgeInsets.only(right: 3),
                                decoration: boxDecoration,
                                child: Text("默认",
                                    style: TextStyle(
                                        fontSize: 12,
                                        color: Color(
                                                int.parse('fa436a', radix: 16))
                                            .withAlpha(255))),
                              ),
                            ),
                            Text(data.detail,
                                style: TextStyle(
                                    fontSize: 15,
                                    color: Color(int.parse('303133', radix: 16))
                                        .withAlpha(255))),
                          ],
                        ),
                        const SizedBox(
                          height: 10,
                        ),
                        Text("${data.consignee} ${data.phone}",
                            style: TextStyle(
                                fontSize: 14,
                                color: Color(int.parse('909399', radix: 16))
                                    .withAlpha(255))),
                      ],
                    ),
                  ),
                  Row(
                    children: [
                      InkWell(
                        onTap: () {
                          // 进入编辑页
                          Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) => const AddressAdd(),
                            ),
                          );
                        },
                        child: Image.asset(
                          "assets/images/edit.png",
                          height: 20,
                          width: 22,
                        ),
                      ),
                      const SizedBox(
                        width: 15,
                      ),
                      InkWell(
                        onTap: () {
                          // 删除地址
                          Provider.of<AddressModel>(context, listen: false)
                              .removeAddress(data.id);
                        },
                        child: Image.asset(
                          "assets/images/delete.png",
                          height: 20,
                          width: 22,
                        ),
                      )
                    ],
                  )
                ],
              ),
            ),
          );
        });
  }

  // 优惠券列表
  ListView buildCouponList(BuildContext context, ScrollController controller) {
    List<CouponData> couponListData =
        Provider.of<CartModel>(context, listen: false).availableCoupons;
    return ListView.builder(
      controller: controller,
      shrinkWrap: true,
      itemCount: couponListData.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: () {
            Provider.of<CartModel>(context, listen: false)
                .selectCoupon(couponListData[index].id);
            Navigator.pop(context); // 关闭底部弹出框
          },
          child: Container(
            padding: const EdgeInsets.all(15),
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  width: 5,
                  color: Color(int.parse('f5f5f5', radix: 16)).withAlpha(255),
                ),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            couponListData[index].name,
                            style: TextStyle(
                              fontSize: 16,
                              color: Color(int.parse('303133', radix: 16))
                                  .withAlpha(255),
                            ),
                          ),
                          Text(
                            "有效期至${couponListData[index].endTime}",
                            style: TextStyle(
                              fontSize: 12,
                              color: Color(int.parse('909399', radix: 16))
                                  .withAlpha(255),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Column(
                      children: [
                        Row(
                          children: [
                            Text(
                              "￥",
                              style: TextStyle(
                                fontSize: 17,
                                color: Color(int.parse('fa436a', radix: 16))
                                    .withAlpha(255),
                              ),
                            ),
                            Text(
                              "${couponListData[index].discount}",
                              style: TextStyle(
                                fontSize: 22,
                                color: Color(int.parse('fa436a', radix: 16))
                                    .withAlpha(255),
                              ),
                            ),
                          ],
                        ),
                        Text(
                          "满${couponListData[index].threshold}可用",
                          style: TextStyle(
                            fontSize: 13,
                            color: Color(int.parse('707070', radix: 16))
                                .withAlpha(255),
                          ),
                        ),
                      ],
                    )
                  ],
                ),
                Container(
                  height: 5,
                ),
                Text(
                  "全场通用",
                  style: TextStyle(
                    fontSize: 12,
                    color: Color(int.parse('909399', radix: 16)).withAlpha(255),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  CustomScrollView buildOrderDetail() {
    return CustomScrollView(
      shrinkWrap: true,
      slivers: [
        buildAddress(),
        buildProductTitle(),
        buildProductList(4),
        buildCoupon(),
        buildOrderInfo(),
      ],
    );
  }

  // 用户收货地址
  SliverPadding buildAddress() {
    AddressData address =
        Provider.of<AddressModel>(context, listen: true).selectedAddress!;
    var border = BorderSide(
        width: 5, color: Color(int.parse('f5f5f5', radix: 16)).withAlpha(255));
    var boxDecoration = BoxDecoration(
      color: Colors.white,
      border: Border(bottom: border),
    );

    return SliverPadding(
        padding: const EdgeInsets.all(0),
        sliver: SliverList(
            delegate: SliverChildListDelegate(<Widget>[
          GestureDetector(
            onTap: () {
              _openBottomSheetWithInfo(context, "选择地址");
            },
            child: Container(
              decoration: boxDecoration,
              height: 78,
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Row(
                children: [
                  Image.asset(
                    "assets/images/address.png",
                    height: 24,
                    width: 22,
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text("${address.consignee} ${address.phone}",
                            style: TextStyle(
                                fontSize: 17,
                                color: Color(int.parse('303133', radix: 16))
                                    .withAlpha(255))),
                        const SizedBox(
                          height: 5,
                        ),
                        Text(address.detail,
                            style: TextStyle(
                                fontSize: 14,
                                color: Color(int.parse('909399', radix: 16))
                                    .withAlpha(255))),
                      ],
                    ),
                  ),
                  Image.asset(
                    "assets/images/right_arrow1.png",
                    height: 17,
                    width: 16,
                  )
                ],
              ),
            ),
          ),
        ])));
  }

  // 标题
  SliverPadding buildProductTitle() {
    var border = BorderSide(
        width: 1, color: Color(int.parse('f5f5f5', radix: 16)).withAlpha(255));
    var boxDecoration = BoxDecoration(
      color: Colors.white,
      border: Border(bottom: border),
    );
    return SliverPadding(
        padding: const EdgeInsets.all(0),
        sliver: SliverList(
            delegate: SliverChildListDelegate(<Widget>[
          Container(
              alignment: AlignmentDirectional.centerStart,
              padding: const EdgeInsets.only(left: 15),
              decoration: boxDecoration,
              height: 42,
              child: Text("商品信息",
                  style: TextStyle(
                      fontSize: 15,
                      color: Color(int.parse('606266', radix: 16))
                          .withAlpha(255)))),
        ])));
  }

  // 商品列表
  SliverList buildProductList(int count) {
    List<CartData> flowers =
        Provider.of<CartModel>(context, listen: true).getCheckFlower();
    return SliverList.builder(
        itemCount: flowers.length,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            color: Colors.white,
            padding: const EdgeInsets.all(15),
            child: Row(
              children: [
                CachedImageWidget(
                  70,
                  70,
                  flowers[index].coverUrl,
                  fit: BoxFit.cover,
                ),
                const SizedBox(
                  width: 8,
                ),
                Expanded(
                    child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(flowers[index].name,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 15,
                            color: Color(int.parse('303133', radix: 16))
                                .withAlpha(255))),
                    const SizedBox(
                      height: 6,
                    ),
                    Text(flowers[index].ename,
                        maxLines: 1,
                        style: TextStyle(
                            fontSize: 13,
                            color: Color(int.parse('909399', radix: 16))
                                .withAlpha(255))),
                    const SizedBox(
                      height: 6,
                    ),
                    Text(
                        "￥${flowers[index].price} x ${flowers[index].number} ${flowers[index].unit}",
                        style: TextStyle(
                            fontSize: 16,
                            color: Color(int.parse('303133', radix: 16))
                                .withAlpha(255))),
                  ],
                ))
              ],
            ),
          );
        });
  }

  SliverPadding buildCoupon() {
    var border = BorderSide(
        width: 5, color: Color(int.parse('f5f5f5', radix: 16)).withAlpha(255));
    var boxDecoration = BoxDecoration(
      color: Colors.white,
      border: Border(top: border),
    );
    return SliverPadding(
        padding: const EdgeInsets.all(0),
        sliver: SliverList(
            delegate: SliverChildListDelegate(<Widget>[
          Container(
            margin: const EdgeInsets.only(top: 5),
            padding: const EdgeInsets.symmetric(horizontal: 15),
            decoration: boxDecoration,
            height: 45,
            child: Row(
              children: [
                Container(
                  width: 20,
                  height: 20,
                  alignment: Alignment.center,
                  color: Color(int.parse('f85e52', radix: 16)).withAlpha(255),
                  child: const Text("券",
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.white,
                      )),
                ),
                const SizedBox(
                  width: 5,
                ),
                Expanded(
                  child: Text("优惠券",
                      style: TextStyle(
                          fontSize: 13,
                          color: Color(int.parse('707070', radix: 16))
                              .withAlpha(255))),
                ),
                InkWell(
                  onTap: () {
                    _openBottomSheetWithInfo(context, "选择优惠券");
                  },
                  child: Text("选择优惠券",
                      style: TextStyle(
                          fontSize: 13,
                          color: Color(int.parse('fa436a', radix: 16))
                              .withAlpha(255))),
                ),
              ],
            ),
          ),
          Divider(
            height: 1,
            indent: 15,
            color: Color(int.parse('f5f5f5', radix: 16)).withAlpha(255),
          ),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.symmetric(horizontal: 15),
            height: 45,
            child: Row(
              children: [
                Container(
                  width: 20,
                  height: 20,
                  alignment: Alignment.center,
                  color: Color(int.parse('ffaa0e', radix: 16)).withAlpha(255),
                  child: const Text("积",
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.white,
                      )),
                ),
                const SizedBox(
                  width: 5,
                ),
                Expanded(
                  child: Text("积分抵扣",
                      style: TextStyle(
                          fontSize: 13,
                          color: Color(int.parse('707070', radix: 16))
                              .withAlpha(255))),
                ),
                Text("0",
                    style: TextStyle(
                        fontSize: 13,
                        color: Color(int.parse('fa436a', radix: 16))
                            .withAlpha(255))),
              ],
            ),
          )
        ])));
  }

  SliverPadding buildOrderInfo() {
    var border = const BorderSide(
        width: 5, color: MyColors.driver);
    var boxDecoration = BoxDecoration(
      color: MyColors.white,
      border: Border(top: border),
    );
    return SliverPadding(
        padding: const EdgeInsets.all(0),
        sliver: SliverList(
            delegate: SliverChildListDelegate(<Widget>[
          Container(
            decoration: boxDecoration,
            padding: const EdgeInsets.symmetric(horizontal: 15),
            child: Column(
              children: [
                SizedBox(
                  height: 45,
                  child: Row(
                    children: [
                      const Expanded(
                          child: Text("商品合计",
                              style: TextStyle(
                                  fontSize: 13,
                                  color: MyColors.name))),
                      Text(
                          "￥${Provider.of<CartModel>(context, listen: true).getFlowerAllPrice()}",
                          style: const TextStyle(
                              fontSize: 13,
                              color: MyColors.normal)),
                    ],
                  ),
                ),
                const Divider(
                  height: 1,
                  color: MyColors.driver,
                ),
                const SizedBox(
                  height: 45,
                  child: Row(
                    children: [
                      Expanded(
                          child: Text("运费",
                              style: TextStyle(
                                  fontSize: 13,
                                  color: MyColors.normal))),
                      Text("￥0",
                          style: TextStyle(
                              fontSize: 13,
                              color: MyColors.normal)),
                    ],
                  ),
                ),
                const Divider(
                  height: 1,
                  color: MyColors.driver,
                ),
                const SizedBox(
                  height: 45,
                  child: Row(
                    children: [
                      Expanded(
                          child: Text("活动优惠",
                              style: TextStyle(
                                  fontSize: 13,
                                  color: MyColors.name))),
                      Text("-￥0",
                          style: TextStyle(
                              fontSize: 13,
                              color: MyColors.boyPink)),
                    ],
                  ),
                ),
                const Divider(
                  height: 1,
                  color: MyColors.driver,
                ),
                SizedBox(
                  height: 45,
                  child: Row(
                    children: [
                      const Expanded(
                          child: Text("优惠券",
                              style: TextStyle(
                                  fontSize: 13,
                                  color: MyColors.name))),
                      Text(
                          "-￥${Provider.of<CartModel>(context, listen: true).couponPrice}",
                          style: const TextStyle(
                              fontSize: 13,
                              color:  MyColors.boyPink)),
                    ],
                  ),
                ),
                const Divider(
                  height: 1,
                  color: MyColors.driver,
                ),
                const SizedBox(
                  height: 45,
                  child: Row(
                    children: [
                      Expanded(
                          child: Text("积分抵扣",
                              style: TextStyle(
                                  fontSize: 13,
                                  color: MyColors.name))),
                      Text("-￥0",
                          style: TextStyle(
                              fontSize: 13,
                              color: MyColors.boyPink)),
                    ],
                  ),
                ),
                const Divider(
                  height: 1,
                  color: MyColors.driver,
                ),
                SizedBox(
                  height: 45,
                  child: Row(
                    textBaseline: TextBaseline.alphabetic,
                    children: [
                      const Text("备注",
                          style: TextStyle(
                              fontSize: 13,
                              color: MyColors.name)),
                      const SizedBox(
                        width: 10,
                      ),
                      Expanded(
                        child: TextField(
                          controller: _remarkController,
                          decoration: const InputDecoration(
                              hintText: "请填写备注信息",
                              contentPadding: EdgeInsets.zero,
                              isDense: true,
                              border: InputBorder.none,
                              hintStyle: TextStyle(
                                  fontSize: 12,
                                  textBaseline: TextBaseline.alphabetic)),
                        ),
                      )
                    ],
                  ),
                ),
                const SizedBox(
                  height: 45,
                ),
              ],
            ),
          )
        ])));
  }

  // 底部提交订单部分
  Container buildSubmit() {
    double price =
        Provider.of<CartModel>(context, listen: true).getDiscountPrice();
    return Container(
      padding: const EdgeInsets.only(left: 15),
      decoration: const BoxDecoration(
        color: MyColors.white,
        border: Border.symmetric(
          vertical: BorderSide(
            color: MyColors.border, //边框颜色
            width: 1, //边框宽度)
          ),
        ),
        boxShadow: [
          BoxShadow(
            blurRadius: 2, //阴影范围
            spreadRadius: 1, //阴影浓度
            color: MyColors.title, //阴影颜色
          ),
        ],
      ),
      height: 45,
      width: MediaQuery.of(context).size.width,
      child: Row(
        children: [
          Expanded(
            flex: 2,
            child: Row(
              children: [
                const Text("实付款 ",
                    style: TextStyle(
                        fontSize: 15,
                        color: MyColors.name)),
                const Text("￥",
                    style: TextStyle(
                        fontSize: 15,
                        color: MyColors.boyPink)),
                Text(price.toString(),
                    style: const TextStyle(
                        fontSize: 18,
                        color: MyColors.boyPink)),
              ],
            ),
          ),
          Expanded(
              flex: 1,
              child: InkWell(
                onTap: () {
                  handleSubmitOrder();
                },
                child: Container(
                  alignment: Alignment.center,
                  height: 140,
                  decoration: const BoxDecoration(
                    color: MyColors.red,
                  ),
                  child: const Text(
                    '提交订单',
                    style: TextStyle(color: MyColors.white, fontSize: 16),
                  ),
                ),
              ))
        ],
      ),
    );
  }
}
